package com.fone.player.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;

import com.fone.player.ApplicationManage;
import com.fone.player.bean.BindData;
import com.fone.player.bean.LoginData;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.LoginspaceRst;
import com.fone.player.client.Request;
import com.fone.player.sns.ISNSLoginManager;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.sns.bean.SNSUserInfo;

public class LoginUtil {
	
	private static final String TAG = "LoginUtil";
	
	public static boolean checkEmailAndMobile(String userName) {
		boolean flag = false;
		if (checkEmail(userName) || checkMobile(userName)) {
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 判断email
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
//			String check = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
			String check = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			L.i("验证邮箱地址错误", e.getMessage());
			flag = false;
		}
		return flag;
	}

	public static boolean checkPassword(String pwd) {
		boolean flag = false;
		if (pwd.length() >= 6 && pwd.length() <= 24
				&& pwd.matches("[0-9A-Za-z]*")) {
			flag = true;
		}
		return flag;
	}

	public static boolean checkMobile(String mobiles) {
//		Pattern p = Pattern
//				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Pattern p = Pattern
				.compile("^(1[3,5,7,8][0-9])\\d{8}$");
		Matcher m = p.matcher(mobiles);
		L.v(TAG, "isMobileNO", "m.matches(): " + m.matches());
		return m.matches();
	}

	public static boolean checkNickName(String nickName) {
		boolean flag = false;
		if (nickName.trim().length() == 0) {
			return flag;
		}

		if (nickName.length() >= 1 && nickName.length() <= 25) {
			flag = true;
		}
		return flag;
	}
	
	public static boolean checkUserName(String userName){
		boolean flag = false;
		if (userName.trim().length() == 0) {
			return flag;
		}
		if(checkEmailAndMobile(userName)){
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 第三方登录 封装 LoginData
	 * @param user
	 * @return
	 */
	public static LoginData getLoginData(SNSUserInfo user) {
		
		LoginData data = null;
		if(user!=null){
			data = new LoginData();
			switch (user.snsType) {
			case ISNSLoginManager.TENCENT_QQ_TYPE:
				data.fp = "qq";
				break;

			case ISNSLoginManager.TENCENT_WEIBO_TYPE:
				data.fp = "tencent";
				break;

			case ISNSLoginManager.SINA_WEIBO_TYPE:
				data.fp = "sina";
				break;
				
			case ISNSLoginManager.TENCENT_WEIXIN_TYPE:
				data.fp = "wechat";
				break;
			}	
			data.tx = user.headPic;
			if(user.nickName!=null){
				data.nickname = new String(Base64.encode(user.nickName.getBytes(),
					Base64.URL_SAFE | Base64.NO_WRAP));
			}
			data.sid = user.thirdPlatformID;
			data.access_token = user.accessToken;
			data.expiresin = user.expiresIn;
			data.expirestime = user.expiresTime;
		}
		return data;
		
	}
	
	public static LoginData getLoginData(String userName,String psw){
		LoginData data = new LoginData();
		data.userid = userName;
		if (psw != null) {
			data.pwd = FoneUtil.Md5(psw);
		}
		return data;
	}
	
	public static BindData getBinData(SNSUserInfo user){
		BindData data = null;
		if(user!=null){
			data = new BindData();
			switch (user.snsType) {
			case ISNSLoginManager.TENCENT_QQ_TYPE:
				data.fp = "qq";
				break;

			case ISNSLoginManager.TENCENT_WEIBO_TYPE:
				data.fp = "tencent";
				break;

			case ISNSLoginManager.SINA_WEIBO_TYPE:
				data.fp = "sina";
				break;
			}	
			data.tx = user.headPic;
			if(user.nickName!=null){
				data.nickname = new String(Base64.encode(user.nickName.getBytes(),
					Base64.URL_SAFE | Base64.NO_WRAP));
			}
			data.sid = user.thirdPlatformID;
			data.access_token = user.accessToken;
			data.expiresin = user.expiresIn;
			data.expirestime = user.expiresTime;
		}
		return data;
	}
	
	
	/**
	 * 头像图片转换字符串    
	 * @param path
	 * @return
	 */
	public static String getHeadPicString(String path){
		String picString = null;
		if(TextUtils.isEmpty(path)){
			return null;
		}
		File mfile = new File(path);
		if(!mfile.exists()){
			return null;
		}
		FileInputStream fis = null;
		ByteArrayOutputStream baos = null;
		try {
			byte[] temp = new byte[1024];
			int flag = -1;
			
			fis = new FileInputStream(mfile);
			baos = new ByteArrayOutputStream();
			
			while((flag=fis.read(temp))!=-1){
				baos.write(temp, 0, flag);
			}
			byte[] data = baos.toByteArray();
			picString = FoneUtil.Base64Encode(data);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if(fis!=null){
						fis.close();
						fis = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if(baos!=null){
						baos.close();
						baos = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
		return picString;
	}
	
	
	/**
	 * 自动登录
	 */
	public static void autoLogin(){
		L.v(TAG, "autoLogin","start !!!");
		if(FoneUtil.isNetOk(ApplicationManage.getGlobalContext())){
			L.v(TAG, "autoLogin","start !!! logining ");
			Request.getInstance().loginspace(1, 0, 0, null, new LoginCallBack());
		}
	}
	
	private static class LoginCallBack implements Callback<LoginspaceRst> {

		@Override
		public void onSuccess(final LoginspaceRst t) {
			L.v(TAG, "autoLogin LoginCallBack onSuccess", t.toString());
			if (t.result != 0) {
				if (t.error != null) {
					L.v(TAG, "autoLogin onSuccess", "errorcode : "+ t.error.errorcode);
					try {
						switch (Integer.valueOf(t.error.errorcode)) {
						case 110:// 用户名不存在
						case 111:// 用户名或密码错误
						case 117:// 请检查用户名
//							FoneUtil.showToast(ApplicationManage.getGlobalContext(), "帐号密码不匹配");
							break;
						default:
//							FoneUtil.showToast(ApplicationManage.getGlobalContext(), "登录失败");
							break;
						}
					} catch (Exception e) {
						L.v(TAG, "autoLogin LoginCallBack onSuccess", e.getMessage()+"");
					}
					return;
				}
			}
			// 本地化用户信息
			new Thread() {
				@Override
				public void run() {
					UserInfoManager.saveLoginUserInfo(t,
							UserInfoManager.UPDATE_USERINFO);
					L.v(TAG, "autoLogin LoginCallBack onSuccess", " autoLogin success");
				};
			}.start();

		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG,
					"autoLogin LoginCallBack onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());
		}
	}
}
